<?php
/**
 * Created by PhpStorm.
 * User: wangsentao
 * Date: 2018/2/2
 * Time: 上午11:25
 */

namespace app\admin\controller\v1;

use app\admin\controller\Factory;
use app\admin\controller\Fun;
use app\admin\controller\Oauth;
use think\Request;
use think\Db;
use app\api\controller\Errorcode;

/**
 * 所有资源类接都必须继承基类控制器
 *
 */
class Base
{
    protected $param;

    protected $adminRules,$HrefId;

    protected $page_size = 3;//列表的每页个数

    protected $sort_type = [
        '0' => 'asc' ,
        '1' => 'desc'
    ];

    public function __construct($param)
    {
        $this->param = $param;
        $this->checkAuth();
        if(!$this->checkAuth()){
            return Fun::error('0','权限过期');
        }
        
        //权限管理
        $req = Request::instance();
        $head = $req->header();
        define('MODULE_NAME',$head['interface']);
        define('ACTION_NAME',$param['command']);
        //当前操作权限ID
        if($param['acc_id']){
            //根据acc_id查询user_type,如果是公司员工判断权限
            $user = DB::name('admin_user')->where(['acc_id'=>$param['acc_id']])->field('user_type')->find(); 
            if ($user['user_type']==0) {
                $this->HrefId = db('auth_rule')->where('href',MODULE_NAME.'/'.ACTION_NAME)->value('id');
                //当前管理员权限
                $map['a.acc_id'] = $param['acc_id'];
                $rules=Db::table(config('database.prefix').'admin_user')->alias('a')
                    ->join('auth_group ag','a.group_id = ag.group_id','left')
                    ->where($map)
                    ->value('ag.rules');
                $this->adminRules = explode(',',$rules);
                if($this->HrefId){
                    if(!in_array($this->HrefId,$this->adminRules)){
                        $result = ['code'=>'333330','msg'=>'您无此操作权限!'];
                        echo json_encode($result);
                        die;
                    }
                }
            }
        }        
        if(!empty($this->param['page_size'])&&intval($this->param['page_size'])>0){
            $this->page_size = $this->param['page_size'];
        }
    }


    private function checkAuth()
    {
        $baseAuth = Factory::getInstance(\app\admin\controller\Oauth::class);
        return $baseAuth->authenticate($this->param);
    }
}